
import sys

from ctypes import *
from common_c import load_library

libtlg = load_library('libtlg')

class tlg_t(Structure):
	_fields_ = (('width',  c_int),
	            ('height', c_int),
	            ('version', c_int),
	            ('colors', c_int),
	            ('buffer', POINTER(c_uint8)),
				)

def read_tlg(path):
	if isinstance(path, unicode):
		path = path.encode(sys.getfilesystemencoding())
	tlg = libtlg.read_tlg_file(path)
	if not tlg:
		raise Exception('read_tlg error')
	return cast(tlg, POINTER(tlg_t)).contents

def delete_tlg(tlg):
	libtlg.delete_tlg(pointer(tlg))

def read_tlg_raw(bytes):
	assert isinstance(bytes, str)
	tlg = libtlg.read_tlg(bytes, len(bytes))
	if not tlg:
		raise Exception('read_tlg error')
	return cast(tlg, POINTER(tlg_t)).contents

def tlg_string_to_bmp_string(tlg):
	t = read_tlg_raw(tlg)
	try:
		buffer = create_string_buffer(0x36+t.width*t.height*t.colors)
		n = libtlg.tlg_to_bmp_ibuffer(pointer(t), buffer)
		if n:
			raise RuntimeError('tlg_to_bmp_ibuffer failed')
		return buffer.raw
	finally:
		delete_tlg(t)

try:
	libtlg2png = load_library('libtlg2png')
	def write_png(tlg, path):
		if isinstance(path, unicode):
			path = path.encode(sys.getfilesystemencoding())
		code = libtlg2png.tlg_to_png(pointer(tlg), path)
		if code:
			raise Exception('tlg_to_png error')
	def tlg_to_png(tlg_path, png_path):
		if isinstance(tlg_path, unicode):
			tlg_path = tlg_path.encode(sys.getfilesystemencoding())
		if isinstance(png_path, unicode):
			png_path = png_path.encode(sys.getfilesystemencoding())
		code = libtlg2png.tlg_file_to_png_file(tlg, path)
		if code:
			raise Exception('tlg_file_to_png_file error')
except:
	write_png = None
	tlg_to_png = None



